package com.linkai.jacklinmap.Activity;

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.view.ViewCompat;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.Toast;

import com.linkai.jacklinmap.Database.MyHelper;
import com.linkai.jacklinmap.Fragment.MineFragment;
import com.linkai.jacklinmap.R;

/**
 * 创建日期：2021/6/10 17:32
 * @author 林凯
 * 文件名称： LoginActivity.java
 * 类说明： 登录界面
 */
public class LoginActivity extends AppCompatActivity implements View.OnClickListener, TextWatcher {

    Button login_login,login_register;
    EditText et_uname, et_password;
    ImageButton login_delete_1, login_delete_2;

    // 数据库操作
    SQLiteDatabase db;
    MyHelper dbHelper;

    String uid, uname, password;

    // 发送广播用到
    private IntentFilter intentFilter;
    private NetworkChangeReceiver networkChangeReceiver;

    // 对话框
    AlertDialog alert;
    AlertDialog.Builder builder;

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        dbHelper = new MyHelper(LoginActivity.this);

        init();

        // 创建 IntentFilter 并添加 action，表明监听什么类型的广播。这里选择监听系统的网络状态
        intentFilter = new IntentFilter();
        intentFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
        networkChangeReceiver = new NetworkChangeReceiver();
        // 注册动态广播监听器
        registerReceiver(networkChangeReceiver, intentFilter);


        // 设置有颜色的状态栏
        setStatusBarColor(this, Color.parseColor("#1292d0"));
    }

    private void init() {

        // 登录注册按钮
        login_login = findViewById(R.id.login_login);
        login_register = findViewById(R.id.login_register);

        // 文本输入框
        et_uname = findViewById(R.id.login_uname);
        et_password = findViewById(R.id.login_password);

        // 删除文本按钮
        login_delete_1 = findViewById(R.id.login_delete_1);
        login_delete_2 = findViewById(R.id.login_delete_2);
        // 设置为隐藏
        login_delete_1.setVisibility(View.GONE);
        login_delete_2.setVisibility(View.GONE);

        // 登录注册按钮添加监听事件
        login_login.setOnClickListener(this::onClick);
        login_register.setOnClickListener(this::onClick);

        // 文本框添加监听事件
        et_uname.addTextChangedListener(this);
        et_password.addTextChangedListener(this);

        // 删除文本按钮添加监听事件
        login_delete_1.setOnClickListener(this::onClick);
        login_delete_2.setOnClickListener(this::onClick);

        // 记住密码
        // 获取数据，显示用户名
        SharedPreferences mSharedPreferences = this.getSharedPreferences("userinfo", Context.MODE_PRIVATE);
        final String rememberUname = mSharedPreferences.getString("uname", "");
        final String rememberPassword = mSharedPreferences.getString("password", "");
        et_uname.setText(rememberUname);
        et_password.setText(rememberPassword);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.login_login:

                db = dbHelper.getReadableDatabase();

                uname = et_uname.getText().toString();
                password = et_password.getText().toString();

                Cursor cursor = db.rawQuery("select u_id, u_name,u_password from userinfo where u_name = ? and u_password=?", new String[]{ uname, password });

                if (cursor.getCount() == 0) {
                    Toast.makeText(getApplicationContext(), "账号或密码错误！", Toast.LENGTH_SHORT).show();
                    cursor.close();
                    db.close();
                    break;
                }

                // 获取用户id，方便后续操作
                cursor.moveToFirst();
                uid = cursor.getString(0);
                System.out.println("login uid = " + uid);


                // 关闭数据库连接
                cursor.close();
                db.close();

                Toast.makeText(getApplicationContext(), "登录成功！", Toast.LENGTH_SHORT).show();


                // 登录成功之后，用 SharedPreferences 保存用户登录参数，同时实现向 Fragment 通信
                SharedPreferences mSharedPreferences=getSharedPreferences("userinfo",Context.MODE_PRIVATE);
                SharedPreferences.Editor editor=mSharedPreferences.edit();
                editor.putString("uname",uname).commit();
                editor.putString("u_id", uid).commit();
                editor.putString("password", password).commit();



                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        //do something

                        startActivity(new Intent(LoginActivity.this, HomeActivity.class));
                        // 销毁当前活动
                        finish();
                    }
                }, 500);    //延时1s执行

                break;
            case R.id.login_register:
                startActivity(new Intent(this, RegisterActivity.class));
                break;
            case R.id.login_delete_1:
                et_uname.setText("");
                break;
            case R.id.login_delete_2:
                et_password.setText("");
                break;
        }
    }

    // 实现 TextWatcher 需要重写的3个方法（EditText 的监听事件）
    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    // 监听 EditText 文本发生改变，显示删除按钮
    @Override
    public void afterTextChanged(Editable s) {

        if (et_uname.getText().length() != 0) {
            login_delete_1.setVisibility(View.VISIBLE);
        } else {
            login_delete_1.setVisibility(View.GONE);
        }

        if (et_password.getText().length() != 0) {
            login_delete_2.setVisibility(View.VISIBLE);
        } else {
            login_delete_2.setVisibility(View.GONE);
        }
    }


    // 广播接收器，内部类，继承 BroadcastReceiver,
    class NetworkChangeReceiver extends BroadcastReceiver {

        // 每当网络状态发生变化，onReceive 方法得到执行
        @Override
        public void onReceive(Context context, Intent intent) {
            // 获得一个系统服务类
            ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
            // 通过这个服务类获取网络信息
            NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
            if (networkInfo != null && networkInfo.isAvailable()) {
//                Toast.makeText(context, "网络可用", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(context, "网络不可用", Toast.LENGTH_SHORT).show();


                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        //do something
                        showAlert();
                    }
                }, 1000);    //延时1s执行



            }
        }
    }


    public void showAlert() {
        builder = new AlertDialog.Builder(this);

        alert = builder.setIcon(R.mipmap.icon_warning)
                .setTitle("系统提示：")
                .setMessage("检测到网络链接未打开，请打开网络链接！")
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                    }
                })
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
//                                Toast.makeText(getApplicationContext(), "注销成功", Toast.LENGTH_SHORT).show();
                    }
                }).create();             //创建AlertDialog对象
        alert.show();                    //显示对话框
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 动态注册的广播接收器记得取消注册
        unregisterReceiver(networkChangeReceiver);
    }


    // 设置状态栏透明
    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    static void setStatusBarColor(Activity activity, int statusColor) {
        Window window = activity.getWindow();
        //取消状态栏透明
        window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        //添加Flag把状态栏设为可绘制模式
        window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
        //设置状态栏颜色
        window.setStatusBarColor(statusColor);
        //设置系统状态栏处于可见状态
        window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_VISIBLE);
        //让view不根据系统窗口来调整自己的布局
        ViewGroup mContentView = (ViewGroup) window.findViewById(Window.ID_ANDROID_CONTENT);
        View mChildView = mContentView.getChildAt(0);
        if (mChildView != null) {
            ViewCompat.setFitsSystemWindows(mChildView, false);
            ViewCompat.requestApplyInsets(mChildView);
        }
    }



}